Working with Dates and Times Using datetime in Python
Course: Python Training
Topic: Working with Dates and Times Using datetime
Course Link: Python Training Course – JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Dates and Times in Python
Dates and times are important in many Python applications, including appointment scheduling, employee attendance, report generation, payment processing, event management, logging, and data analysis. Python provides the built-in datetime module to create, manipulate, compare, format, and parse date and time values.
The datetime module provides classes such as date, time, datetime, timedelta, and timezone. These classes allow developers to represent calendar dates, times of day, complete timestamps, durations, and time-zone offsets.
Example: Getting the Current Date and Time
from datetime import datetime
current_datetime = datetime.now()
print("Current date and time:", current_datetime)
print("Current year:", current_datetime.year)
print("Current month:", current_datetime.month)
print("Current day:", current_datetime.day)
The datetime.now() method returns the current local date and time as a datetime object. The exact output depends on the system's clock and local time-zone configuration.
2. Importing the datetime Module
The datetime module is included in Python's standard library, so it does not require a separate installation.
Import the Entire Module
import datetime
today = datetime.date.today()
print(today)
Import Specific Classes
from datetime import date, time, datetime, timedelta
today = date.today()
current_time = datetime.now().time()
print("Today:", today)
print("Current time:", current_time)
Importing specific classes can make code more concise. However, remember that the class named datetime and the module named datetime have the same name, so use imports consistently to avoid confusion.
3. Main Classes in the datetime Module
| Class |
Description |
Example |
date |
Represents a calendar date with year, month, and day. |
date(2026, 10, 22) |
time |
Represents a time of day with hours, minutes, seconds, and optional microseconds. |
time(14, 30, 0) |
datetime |
Combines a calendar date and a time of day. |
datetime(2026, 10, 22, 14, 30) |
timedelta |
Represents a duration or difference between date and time values. |
timedelta(days=7) |
timezone |
Represents a fixed offset from UTC. |
timezone.utc |
4. Working with the date Class
The date class represents a calendar date without a time of day. It stores three main attributes: year, month, and day.
Creating a Date Object
from datetime import date
my_date = date(2026, 10, 22)
print(my_date)
print("Year:", my_date.year)
print("Month:", my_date.month)
print("Day:", my_date.day)
Output
2026-10-22
Year: 2026
Month: 10
Day: 22
The arguments are supplied in the order year, month, and day. Python validates the values and raises a ValueError when the date is invalid.
Getting Today's Date
from datetime import date
today = date.today()
print("Today's date:", today)
date.today() returns the current local calendar date according to the system's time configuration.
Finding the Day of the Week
from datetime import date
some_date = date(2026, 10, 22)
print("Weekday number:", some_date.weekday())
print("ISO weekday:", some_date.isoweekday())
The weekday() method returns Monday as 0 and Sunday as 6. The isoweekday() method returns Monday as 1 and Sunday as 7.
5. Working with the time Class
The time class represents a time of day independently of a specific date. It can store hours, minutes, seconds, microseconds, and optional time-zone information.
Creating a Time Object
from datetime import time
meeting_time = time(14, 45, 30)
print(meeting_time)
print("Hour:", meeting_time.hour)
print("Minute:", meeting_time.minute)
print("Second:", meeting_time.second)
Output
14:45:30
Hour: 14
Minute: 45
Second: 30
Creating a Time with Microseconds
from datetime import time
precise_time = time(10, 30, 15, 250000)
print(precise_time)
Output
10:30:15.250000
Python's time object represents a clock time, not an elapsed duration. Use timedelta when you need to represent a period such as 90 minutes or 3 days.
6. Working with the datetime Class
The datetime class combines a date and time into a single object. It is useful for representing appointments, event timestamps, transaction times, and scheduled tasks.
Creating a datetime Object
from datetime import datetime
event = datetime(2026, 10, 22, 15, 30, 45)
print(event)
print("Year:", event.year)
print("Month:", event.month)
print("Day:", event.day)
print("Hour:", event.hour)
print("Minute:", event.minute)
print("Second:", event.second)
Output
2026-10-22 15:30:45
Year: 2026
Month: 10
Day: 22
Hour: 15
Minute: 30
Second: 45
Getting the Current Local Date and Time
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
Getting the Current Date and Time Separately
from datetime import datetime
now = datetime.now()
current_date = now.date()
current_time = now.time()
print("Date:", current_date)
print("Time:", current_time)
The date() method extracts the calendar date, while the time() method extracts the clock time. The resulting time object does not retain the original datetime's time-zone information.
7. Understanding datetime Attributes and Methods
| Attribute or Method |
Purpose |
Example |
year |
Returns the year. |
value.year |
month |
Returns the month number. |
value.month |
day |
Returns the day of the month. |
value.day |
hour |
Returns the hour. |
value.hour |
minute |
Returns the minute. |
value.minute |
second |
Returns the second. |
value.second |
date() |
Extracts the date component. |
value.date() |
time() |
Extracts the time component. |
value.time() |
weekday() |
Returns the weekday index from 0 to 6. |
value.weekday() |
isoweekday() |
Returns the weekday index from 1 to 7. |
value.isoweekday() |
replace() |
Creates a new object with selected components changed. |
value.replace(year=2027) |
strftime() |
Formats a date or time object as text. |
value.strftime("%d-%m-%Y") |
8. Formatting Dates and Times with strftime()
The strftime() method converts a date or time object into a formatted string. The format codes specify which date and time components should appear and how they should be displayed.
Example
from datetime import datetime
now = datetime(2026, 10, 22, 15, 45, 30)
print(now.strftime("%d-%m-%Y"))
print(now.strftime("%Y/%m/%d"))
print(now.strftime("%H:%M:%S"))
print(now.strftime("%A, %d %B %Y"))
Output
22-10-2026
2026/10/22
15:45:30
Thursday, 22 October 2026
Common strftime() Format Codes
| Format Code |
Meaning |
Example |
%Y |
Four-digit year |
2026 |
%y |
Two-digit year |
26 |
%m |
Month number |
10 |
%B |
Full month name |
October |
%b |
Abbreviated month name |
Oct |
%d |
Day of the month |
22 |
%A |
Full weekday name |
Thursday |
%a |
Abbreviated weekday name |
Thu |
%H |
Hour in 24-hour format |
15 |
%I |
Hour in 12-hour format |
03 |
%M |
Minute |
45 |
%S |
Second |
30 |
%f |
Microsecond |
000000 |
%p |
AM or PM marker |
PM |
%j |
Day of the year |
295 |
%z |
UTC offset |
+0530 |
%Z |
Time-zone name |
UTC |
Some format-code details depend on the platform's C library. For portable application output, choose common format codes and test them in the environments where the code will run.
9. Converting Strings into Dates with strptime()
The strptime() method parses a string into a date or datetime object according to a specified format. The input string must match the format's expected structure.
Example: Parsing a Date String
from datetime import datetime
date_text = "22-10-2026"
parsed_date = datetime.strptime(date_text, "%d-%m-%Y")
print(parsed_date)
print(type(parsed_date))
Output
2026-10-22 00:00:00
<class 'datetime.datetime'>
Parsing Date and Time Together
from datetime import datetime
date_text = "22/10/2026 03:45 PM"
parsed_datetime = datetime.strptime(
date_text,
"%d/%m/%Y %I:%M %p"
)
print(parsed_datetime)
Output
2026-10-22 15:45:00
The format string must describe the input correctly. If the text does not match the expected format or contains an invalid date, Python raises a ValueError.
10. Difference Between strftime() and strptime()
| Feature |
strftime() |
strptime() |
| Purpose |
Formats a date/time object as text. |
Parses text into a date/time object. |
| Direction |
Object to string. |
String to object. |
| Input |
A format string. |
A date/time string and a format string. |
| Output |
A string. |
A date/time object. |
| Example |
value.strftime("%Y-%m-%d") |
datetime.strptime(text, "%Y-%m-%d") |
11. Working with timedelta
The timedelta class represents a duration or difference between dates and times. It supports arithmetic operations such as adding days to a date, calculating the time between events, and subtracting hours from a datetime.
Creating a timedelta Object
from datetime import timedelta
duration = timedelta(days=5, hours=3, minutes=30)
print(duration)
Output
5 days, 3:30:00
Adding Days to a Date
from datetime import date, timedelta
start_date = date(2026, 10, 22)
future_date = start_date + timedelta(days=10)
print("Start date:", start_date)
print("Future date:", future_date)
Output
Start date: 2026-10-22
Future date: 2026-11-01
Subtracting Days
from datetime import date, timedelta
today = date(2026, 10, 22)
previous_date = today - timedelta(days=7)
print(previous_date)
Output
2026-10-15
Calculating the Difference Between Two Dates
from datetime import date
start = date(2026, 10, 1)
end = date(2026, 10, 22)
difference = end - start
print("Days between:", difference.days)
Output
Days between: 21
Subtracting two dates produces a timedelta. Its days attribute provides the number of whole days in the duration.
12. Calculating Time Differences
Datetime arithmetic can calculate the duration of a meeting, the elapsed time of a process, or the time remaining before an event.
Example: Meeting Duration
from datetime import datetime
meeting_start = datetime(2026, 10, 22, 10, 0)
meeting_end = datetime(2026, 10, 22, 11, 45)
duration = meeting_end - meeting_start
print("Duration:", duration)
print("Seconds:", duration.total_seconds())
Output
Duration: 1:45:00
Seconds: 6300.0
The total_seconds() method returns the full duration in seconds, including the days component. This is useful when a duration spans multiple days.
13. Comparing Dates and Times
Date and datetime objects can be compared using operators such as <, >, ==, and !=. Comparisons help determine whether a deadline has passed or which event occurs first.
Example: Checking a Deadline
from datetime import date
deadline = date(2026, 11, 1)
submission_date = date(2026, 10, 22)
if submission_date < deadline:
print("Submitted before the deadline")
elif submission_date == deadline:
print("Submitted on the deadline")
else:
print("Submitted after the deadline")
Output
Submitted before the deadline
When comparing datetimes, ensure that both values have compatible time-zone handling. Comparing a naive datetime with an aware datetime raises a TypeError.
14. Replacing Parts of a Date or Time
The replace() method creates a new date or datetime object with selected components changed. It does not modify the original object because these objects are immutable.
Example
from datetime import datetime
original = datetime(2026, 10, 22, 15, 30)
updated = original.replace(year=2027, hour=9, minute=0)
print("Original:", original)
print("Updated:", updated)
Output
Original: 2026-10-22 15:30:00
Updated: 2027-10-22 09:00:00
Use replace() when you want to change specific fields without performing a duration-based calculation. Use timedelta for arithmetic such as adding 30 days.
15. Combining Date and Time Objects
The datetime.combine() method combines a date object and a time object to create a datetime object.
Example
from datetime import date, time, datetime
event_date = date(2026, 10, 22)
event_time = time(16, 30)
event_datetime = datetime.combine(event_date, event_time)
print(event_datetime)
Output
2026-10-22 16:30:00
This method is useful when an application stores an event date and event time separately but needs a complete timestamp for scheduling or comparison.
16. Converting Between datetime and Date Strings
Applications often need to exchange dates and times with APIs, databases, spreadsheets, and configuration files. A consistent string format makes this exchange easier.
Using ISO Format
from datetime import datetime
value = datetime(2026, 10, 22, 15, 30, 0)
formatted = value.isoformat()
print(formatted)
parsed = datetime.fromisoformat(formatted)
print(parsed)
Output
2026-10-22T15:30:00
2026-10-22 15:30:00
The ISO-style representation is useful for data exchange. For timezone-aware values, the formatted string can also include a UTC offset. Parsing support depends on the format and Python version, so follow the expected format of the system receiving the data.
17. Understanding Naive and Aware Datetimes
A naive datetime does not contain enough time-zone information to identify an unambiguous instant. An aware datetime includes usable time-zone information and can identify a specific instant relative to UTC.
| Type |
Description |
Example |
| Naive datetime |
Contains date and clock time but no usable time-zone information. |
datetime(2026, 10, 22, 15, 30) |
| Aware datetime |
Contains date, clock time, and usable time-zone information. |
datetime.now(timezone.utc) |
Example: Current UTC Time
from datetime import datetime, timezone
utc_now = datetime.now(timezone.utc)
print("Current UTC time:", utc_now)
print("Timezone:", utc_now.tzinfo)
For timestamps representing real-world events, timezone-aware datetimes are usually safer than naive datetimes. In particular, use datetime.now(timezone.utc) rather than the deprecated datetime.utcnow() when you need the current UTC time.
18. Working with Fixed Time Zones
The timezone class can represent a fixed offset from UTC. It is suitable for UTC and other fixed offsets, but it does not represent locations whose offsets change over time due to daylight-saving rules or historical changes.
Example: Creating a Fixed UTC Offset
from datetime import datetime, timedelta, timezone
india_offset = timezone(timedelta(hours=5, minutes=30))
local_time = datetime(2026, 10, 22, 15, 30, tzinfo=india_offset)
print(local_time)
print("UTC offset:", local_time.utcoffset())
Output
2026-10-22 15:30:00+05:30
UTC offset: 5:30:00
This example demonstrates a fixed offset of UTC+05:30. For location-based time-zone rules, use the zoneinfo module instead of assuming that a fixed offset captures every rule for a geographic region.
19. Working with Location-Based Time Zones Using zoneinfo
Python's zoneinfo module provides support for IANA time zones, such as Asia/Kolkata and America/New_York. It can apply the relevant offset rules for a particular location and date.
Example: Using the Asia/Kolkata Time Zone
from datetime import datetime
from zoneinfo import ZoneInfo
kolkata_time = datetime.now(ZoneInfo("Asia/Kolkata"))
print("Kolkata time:", kolkata_time)
print("Time zone:", kolkata_time.tzinfo)
This example uses the machine's current clock to obtain the time in the specified time zone. Depending on the operating system or Python environment, an appropriate time-zone database must be available.
Converting UTC Time to Another Time Zone
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_now = datetime.now(timezone.utc)
kolkata_time = utc_now.astimezone(ZoneInfo("Asia/Kolkata"))
print("UTC:", utc_now)
print("Kolkata:", kolkata_time)
The astimezone() method converts an aware datetime to another time zone while preserving the represented instant.
20. Converting Unix Timestamps
A Unix timestamp represents the number of seconds since the Unix epoch, which is 1970-01-01 00:00:00 UTC. Timestamps are frequently used in logs, APIs, databases, and event-processing systems.
Convert a Timestamp to UTC
from datetime import datetime, timezone
timestamp = 1792683000
utc_datetime = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(utc_datetime)
The resulting date and time depend on the timestamp value. Always specify a time zone when the intended interpretation is UTC.
Convert a Datetime to a Timestamp
from datetime import datetime, timezone
event_time = datetime(2026, 10, 22, 10, 0, tzinfo=timezone.utc)
timestamp = event_time.timestamp()
print(timestamp)
For consistent results, use aware datetimes when converting between timestamps and datetime objects. Calling timestamp() on a naive datetime interprets it using local-time assumptions that may differ across machines.
21. Handling Invalid Date Input
User-entered dates may be incomplete, incorrectly formatted, or impossible. Use exception handling to detect invalid input and provide a useful message.
Example
from datetime import datetime
date_text = input("Enter a date (DD-MM-YYYY): ")
try:
parsed_date = datetime.strptime(date_text, "%d-%m-%Y")
print("Valid date:", parsed_date.date())
except ValueError:
print("Invalid date. Please use DD-MM-YYYY.")
The try block attempts to parse the supplied string. If the format is incorrect or the date does not exist, a ValueError is raised and handled by the except block.
22. Practical Project: Calculate an Employee's Working Duration
This example calculates the elapsed time between an employee's check-in and check-out timestamps. It demonstrates parsing, datetime subtraction, and converting a duration into hours and minutes.
from datetime import datetime
check_in_text = "22-10-2026 09:15"
check_out_text = "22-10-2026 17:45"
format_string = "%d-%m-%Y %H:%M"
try:
check_in = datetime.strptime(check_in_text, format_string)
check_out = datetime.strptime(check_out_text, format_string)
if check_out < check_in:
print("Check-out cannot be earlier than check-in.")
else:
duration = check_out - check_in
total_minutes = int(duration.total_seconds() // 60)
hours = total_minutes // 60
minutes = total_minutes % 60
print("Check-in:", check_in)
print("Check-out:", check_out)
print(f"Elapsed duration: {hours} hours and {minutes} minutes")
except ValueError:
print("Invalid date or time format.")
Output
Check-in: 2026-10-22 09:15:00
Check-out: 2026-10-22 17:45:00
Elapsed duration: 8 hours and 30 minutes
This example calculates elapsed time, not paid working hours. A real attendance system may also need to account for breaks, overtime rules, overnight shifts, holidays, and timezone-aware timestamps.
23. Common Errors and Troubleshooting
| Error or Problem |
Cause |
Solution |
ValueError when creating a date |
The year, month, or day is outside the valid calendar range. |
Validate the input and ensure the date exists. |
ValueError from strptime() |
The input text does not match the specified format or contains an invalid date. |
Check the input and format codes. |
TypeError when comparing datetimes |
A naive datetime is compared with an aware datetime. |
Use compatible timezone handling for both values. |
| Incorrect displayed time |
The value is interpreted in the wrong timezone. |
Use timezone-aware values and convert with astimezone(). |
| Unexpected duration |
The calculation ignores breaks or other business rules. |
Apply the application's duration and scheduling rules explicitly. |
| Unexpected timestamp conversion |
A naive datetime is interpreted using the system's local timezone. |
Use an aware datetime when the instant is known to be in UTC or another specific timezone. |
| Missing time-zone data |
The environment lacks the required timezone database. |
Check the environment and install or provide the appropriate timezone data if needed. |
24. Best Practices for Working with Dates and Times
- Use
date for calendar dates, time for clock times, and datetime for complete timestamps.
- Use
timedelta for elapsed durations and date arithmetic.
- Use
strftime() to format date/time objects as strings and strptime() to parse strings.
- Prefer ISO-style date representations for data exchange when suitable for the application.
- Use timezone-aware datetimes for real-world timestamps that must identify a specific instant.
- Use UTC as a common storage and exchange standard when appropriate, then convert to a user's timezone for display.
- Use
zoneinfo for location-based timezone rules rather than relying on fixed offsets when local civil-time rules matter.
- Validate date strings received from users, files, and external services.
- Handle invalid dates with clear error messages.
- Remember that date and datetime objects are immutable; methods such as
replace() return new objects.
- Test date logic around month ends, leap years, year changes, and timezone transitions.
25. Practice Exercises
- Create a date object for your birthday and display its year, month, and day.
- Print the current date and time using
datetime.now().
- Format the current date as
DD-MM-YYYY.
- Parse the string
15-08-2026 using strptime().
- Add 30 days to a given date using
timedelta.
- Calculate the number of days between two dates.
- Calculate the duration between two datetime objects in seconds and minutes.
- Write a program that checks whether a supplied date string is valid.
- Create a UTC-aware datetime and convert it to
Asia/Kolkata using zoneinfo.
- Build a simple event reminder that calculates how many days remain until a specified date.
26. Interview Questions and Answers
Q1. What is the datetime module in Python?
The datetime module is a standard-library module for working with dates, times, durations, and time-zone information.
Q2. What is the difference between date and datetime?
A date object stores a year, month, and day. A datetime object stores those components together with a time of day.
Q3. What is timedelta?
timedelta represents a duration or the difference between date/time values. It can be used to add or subtract time periods.
Q4. What is the difference between strftime() and strptime()?
strftime() converts a date/time object into formatted text, whereas strptime() parses formatted text into a datetime object.
Q5. How do you get the current date in Python?
Import date from datetime and call date.today().
Q6. How do you get the current UTC time?
Use datetime.now(timezone.utc) to obtain a timezone-aware datetime representing the current UTC time.
Q7. What is the difference between naive and aware datetimes?
A naive datetime does not have usable timezone information, while an aware datetime includes information that identifies its relationship to UTC.
Q8. How can you calculate the difference between two dates?
Subtract one date from another. The result is a timedelta object, whose days attribute gives the whole-day difference.
Q9. What does the replace() method do?
replace() returns a new date or datetime object with selected components changed, such as the year, month, hour, or minute.
Q10. Why is timezone handling important?
The same instant can appear as different local clock times in different locations. Correct timezone handling helps applications schedule events and compare timestamps consistently.
Q11. What is zoneinfo used for?
The zoneinfo module supports IANA time zones and applies location-based timezone rules when converting aware datetime values.
Q12. How do you handle invalid date strings?
Use try and except ValueError around parsing operations such as datetime.strptime(), then provide a clear message or request valid input.
27. Quick Revision Checklist
- Understand the
date, time, datetime, timedelta, and timezone classes.
- Create dates and timestamps with the appropriate constructors.
- Retrieve the current date and time.
- Access date and time attributes such as year, month, day, hour, and minute.
- Format objects with
strftime() and parse strings with strptime().
- Add and subtract durations with
timedelta.
- Compare dates and calculate elapsed time.
- Understand naive and timezone-aware datetime values.
- Use
timezone.utc and zoneinfo appropriately.
- Validate user input and handle parsing errors.
28. Conclusion
Python's datetime module provides essential tools for representing and manipulating dates, times, durations, and timestamps. By learning its core classes and methods, developers can create schedules, calculate deadlines, format reports, validate date input, and process timestamps reliably.
Understanding timezone-aware datetimes is especially important when working with distributed applications, APIs, databases, and users in different locations. Combine the core datetime classes with timedelta, formatting methods, and zoneinfo to build dependable date and time functionality.
Continue learning Python: Visit the JustAcademy Python Training Course, register for a course demo, or explore the JustAcademy official website.